# -*- coding: utf-8 -*-
"""
@brief: 测试模拟sort函数
@author: Zhichao Wu
@date: 2022-04-05 00:30:11
@version: 1.0.0
"""
from collections import namedtuple
from datetime import datetime
import unittest
from functools import cmp_to_key

from fluent_python.others.fake_sorted import sorted_fake_by_insert, sorted_fake_by_quick


class SortedFakeTestCase(unittest.TestCase):
    def test_sorted(self):
        data1 = [1, 2, 5, 4, 3]
        self.assertListEqual(sorted(data1), sorted_fake_by_insert(data1))
        self.assertListEqual(sorted(data1), sorted_fake_by_quick(data1))

    def test_different_cmp(self):
        # 坐标
        Position = namedtuple('Position', ['x', 'y'])

        def position_key(pos: Position) -> int:
            """Python 3.0以后支持的 key 参数来处理用户指定的键函数"""
            return pos.x ** 2 + pos.y ** 2

        def compare_two_position(pos1: Position, pos2: Position) -> int:
            """Python 2.x 支持的 cmp 参数来处理用户指定的比较函数"""
            distance = position_key(pos1) - position_key(pos2)
            if distance == 0:  # pos1 = pos2
                return 0
            elif distance < 0:  # pos1 < pos2
                return -1
            else:  # pos1 > pos2
                return 1

        data2 = [Position(1, 1), Position(-1, 1), Position(3, 4), Position(3, 2), Position(1, 2)]
        self.assertListEqual(sorted(data2, key=position_key),
                             sorted_fake_by_quick(data2, key=cmp_to_key(compare_two_position)))


if __name__ == '__main__':
    start_time = datetime.now()
    print("[%s]%s开始运行..." % (start_time.strftime('%Y-%m-%d %H:%M:%S.%f'), __file__))

    unittest.main()

    end_time = datetime.now()
    print(f"[{end_time.strftime('%Y-%m-%d %H:%M:%S.%f')}]{__file__}结束运行.")
    print(f"耗时:{end_time - start_time}")
